<template>
  <div>
    <el-form
      label-width="120px"
      v-loading="loading"
      ref="formRefs"
      :rules="rules"
      :model="sku"
    >
      <el-form-item label="SPU名称">
        <span>{{ spuList.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="SKU名称" v-model="sku.skuName"></el-input>
      </el-form-item>

      <el-form-item label="价格(元)" prop="price">
        <el-input
          placeholder="价格"
          type="number"
          v-model="sku.price"
        ></el-input>
      </el-form-item>

      <el-form-item label="重量(千克)" prop="weight">
        <el-input
          placeholder="重量"
          type="number"
          v-model="sku.weight"
        ></el-input>
      </el-form-item>

      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          placeholder="规格描述"
          type="textarea"
          v-model="sku.skuDesc"
        ></el-input>
      </el-form-item>

      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-form inline label-width="90px">
          <el-form-item
            :label="attr.attrName"
            v-for="attr in attrInfoList"
            :key="attr.id"
          >
            <el-select
              v-model="attr.valueId"
              @change="formRefs?.clearValidate(['skuAttrValueList'])"
            >
              <el-option
                :value="item.id!"
                :label="item.valueName"
                v-for="item in attr.attrValueList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-form>
          <el-form-item
            :label="attr.saleAttrName"
            v-for="attr in spuSaleAttrList"
            :key="attr.id"
          >
            <el-select
              v-model="attr.valueId"
              @change="formRefs?.clearValidate(['skuSaleAttrValueList'])"
            >
              <el-option
                :value="item.id!"
                :label="item.saleAttrValueName"
                v-for="item in attr.spuSaleAttrValueList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          border
          :data="spuImageList"
          @selection-change="selectImageList"
        >
          <el-table-column type="selection"> </el-table-column>
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <el-image :src="row.imgUrl" style="width: 100px" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag v-if="row.imgUrl === sku.skuDefaultImg">默认</el-tag>
              <el-button
                v-else
                type="primary"
                :disabled="!selectedImageList.includes(row)"
                @click="setDefaultImage(row)"
                >设置默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item prop="skuDefaultImg"></el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitCheck"> 保存 </el-button>
        <el-button @click="emit('setShowState', SpuStates.SPU_LIST)">
          取消
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
  import { defineComponent } from "vue";
  import { ElMessage, type FormInstance, type FormRules } from "element-plus";
  import { saveSkuInfoApi } from "@/api/product/sku";
  export default defineComponent({
    name: "SkuForm",
  });
</script>
<script lang="ts" setup>
  import { onMounted, ref, reactive } from "vue";
  import type {
    SkuAttrValueListModel,
    SkuImageModel,
    SkuModel,
    SkuSaleAttrValueListModel,
  } from "@/api/product/model/skuModel";
  import { storeToRefs } from "pinia";
  import { useCategoryStore } from "@/stores/category";
  import { SpuStates } from "../spu";
  import { getSpuImageListApi, getSpuSaleAttrListApi } from "@/api/product/spu";
  import type {
    SpuImageListModel,
    SpuSaleAttrListModel,
    SpuValueModel,
  } from "@/api/product/model/spuModel";
  import { getAttrInfoListApi } from "@/api/product/attr";
  import type { attrListModel } from "@/api/product/model/AttrModel";

  /* 初始化页面  start */
  const loading = ref(false);
  const emit = defineEmits<{
    (e: "setShowState", value: SpuStates): void;
  }>();
  const { category1Id, category2Id, category3Id } = storeToRefs(
    useCategoryStore()
  );
  const prop = defineProps<{
    spuList: SpuValueModel;
  }>();
  // 平台属性列表
  const attrInfoList = ref<attrListModel>([]);
  // SPU图片列表
  const spuImageList = ref<SpuImageListModel>([]);
  // spu销售属性列表
  const spuSaleAttrList = ref<SpuSaleAttrListModel>([]);
  onMounted(async () => {
    loading.value = true;
    const p1 = getAttrInfoListApi({
      category1Id: category1Id.value!,
      category2Id: category2Id.value!,
      category3Id: category3Id.value!,
    });
    const p2 = getSpuImageListApi(prop.spuList.id!);
    const p3 = getSpuSaleAttrListApi(prop.spuList.id!);
    const result = await Promise.all([p1, p2, p3]);
    attrInfoList.value = result[0];
    spuImageList.value = result[1];
    spuSaleAttrList.value = result[2];
    loading.value = false;
  });
  /* 初始化页面  end */

  /* 收集数据 start */
  const sku = reactive<SkuModel>({
    //prop传入
    spuId: prop.spuList.id!,
    tmId: prop.spuList.tmId!,
    category3Id: prop.spuList.category3Id!,
    //v-model收集
    price: 0,
    weight: 0,
    skuName: "",
    skuDesc: "",
    //其他
    skuDefaultImg: "",
    isSale: 1, // 0 下架 / 1 在售
    skuImageList: [],
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
  });

  //收集选中的图片
  const selectedImageList = ref<SpuImageListModel>([]);

  const selectImageList = (values: SpuImageListModel) => {
    selectedImageList.value = values;
  };

  const setDefaultImage = (row: SkuImageModel) => {
    sku.skuDefaultImg = row.imgUrl;
    formRefs.value?.clearValidate(["skuDefaultImg"]);
  };

  /* 收集数据 end */

  /* 表单验证 start */
  const formRefs = ref<FormInstance>();
  const rules: FormRules = {
    skuName: [{ required: true, message: "必须要填SKU名称" }],
    price: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (+value > 0) {
            callback();
          } else {
            callback("价格必须大于0");
          }
        },
      },
    ],
    weight: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (+value > 0) {
            callback();
          } else {
            callback("重量必须大于0");
          }
        },
      },
    ],
    skuDesc: [{ required: true, message: "必须要填规格描述" }],
    skuAttrValueList: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (attrInfoList.value.some((item) => item.valueId)) {
            callback();
          } else {
            callback("必须要选择一个平台属性");
          }
        },
      },
    ],
    skuSaleAttrValueList: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (attrInfoList.value.some((item) => item.valueId)) {
            callback();
          } else {
            callback("必须要选择一个销售属性");
          }
        },
      },
    ],
    skuImageList: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (selectedImageList.value.length > 0) {
            callback();
          } else {
            callback("必须要选择一个图片");
          }
        },
      },
    ],
    skuDefaultImg: [{ required: true, message: "必须要设置一张默认图片" }],
  };

  const submitCheck = async () => {
    await formRefs.value?.validate();

    //处理 skuImageList/skuAttrValueList/skuSaleAttrValueList 数据

    //处理 skuImageList/
    sku.skuImageList = spuImageList.value.map((item) => ({
      imgName: item.imgName,
      imgUrl: item.imgUrl,
      isDefault: item.imgUrl === sku.skuDefaultImg ? "1" : "0",
      spuImgId: item.id!,
    }));

    //处理 skuAttrValueList
    /*
         "skuAttrValueList": [
        {
          "attrId": 0,
          "attrName": "string",
          "id": 0,
          "skuId": 0,
          "valueId": 0,
          "valueName": "string"
        }
      ],
        */
    sku.skuAttrValueList = attrInfoList.value.reduce((p, c) => {
      if (c.valueId) {
        p.push({
          attrId: c.id!,
          valueId: c.valueId,
        });
      }
      return p;
    }, [] as SkuAttrValueListModel);

    /*
       "skuSaleAttrValueList": [
        {

          "id": 0,
          "saleAttrId": 0,
          "saleAttrName": "string",
          "saleAttrValueId": 0,
          "saleAttrValueName": "string",
          "skuId": 0,
          "spuId": 0,

        }
      ],
      */
    //处理 skuSaleAttrValueList 数据
    sku.skuSaleAttrValueList = spuSaleAttrList.value.reduce((p, c) => {
      if (c.valueId) {
        p.push({
          saleAttrValueId: c.valueId!,
        });
      }
      return p;
    }, [] as SkuSaleAttrValueListModel);

    //发送请求 提交数据
    await saveSkuInfoApi(sku);
    ElMessage.success("提交保存成功!");
    //返回spu列表页
    emit("setShowState", SpuStates.SPU_LIST);
  };

  /* 表单验证 end */
</script>

<style lang="scss" scoped></style>
